import { getSingleSessionList, getGroupSessionList, getNoticeList } from '@/store/dispatches.js';
import store from '@/store/index.js'


import Service from '@/utils/Service.js';

// function IM(){
// 	this.socket = '';
// 	this.socketStatus = ''
// }

class ChatIM {
	// socket 进程
	socketTask = null;
	//socket 连接状态
	socketStatus = -99; //-99 未初始化 -10 重连失败 -2 ws断线 -1 ws失败 0 握手成功 1 正在连接 3 登录失败 99 登录成功
	//群聊消息声音播放对象
	groupSoundAudioContext = null;
	//单聊消息声音播放对象
	singleSoundAudioContext = null;
	//用户登陆凭证
	token = null
	//socket地址
	// connectUrl = 'wss://api.dianmianti.com:8282';
	connectUrl = 'wss://api.suisuifa.cn:8181';
	//当前连接次数
	connectTime = 0;
	//链接计时器
	connectTimer = null
	//最大连接次数
	connectMax = 5;
	//是否第一次链接
	connectFirst = true;
	//重连延迟计时器,防止用户手贱不停前置app后置app
	reconnectionDelayTimer = null

	constructor(token = store.state.user.token || null) {
		this.token = token;
		this.connection();

	}

	send(obj) {
		if (this.socketStatus <= 0) {
			return false;
		} else {
			this.socketTask.send(obj)
			return true
		}
	}
	close(obj) {
		console.log('self close');
		clearTimeout(this.connectTimer);
		this.socketTask.close(obj);

		// this.id = null
		// this.socketStatus = -1;
		// this.chatStatusAudioContext = null;
		// this.chatMessageAudioContext = null;
		// this.connectTime = 0;
		// this.connectMax = 5;
		// this.socketTask.close(obj);
		// this.socketTask = null;

	}
	reconnection(force = false) {
		if (force) {
			clearTimeout(this.reconnectionDelayTimer);
			this.reconnectionDelayTimer = setTimeout(() => {
				uni.getNetworkType({
					success: (res) => {
						if (res.networkType == 'none') {
							uni.showToast({
								icon: 'none',
								title: "当前无网络,请检查网络"
							})
						} else {
							this.connectTime = 0
							this.reconnection();
						}
					}
				});
			}, 500)
		} else {
			console.log(this.connectTime)
			if (this.connectTime < this.connectMax) {
				this.connectTimer = setTimeout(() => {
					clearTimeout(this.connectTimer);
					this.connectTime += 1;
					this.connection();
				}, (3000 * (this.connectTime)))
			} else {

				this.socketStatus = -10
			}
		}
	}

	connection() {
		if (!this.token || this.socketStatus == 99 || this.socketStatus == 1) {
			return false;
		}
		this.socketTask && this.socketTask.close()
		this.socketTask = uni.connectSocket({
			url: this.connectUrl,
			success: () => {
				this.groupSoundAudioContext = uni.createInnerAudioContext();
				this.singleSoundAudioContext = uni.createInnerAudioContext();
				this.groupSoundAudioContext.src = "/static/audio/group-sound-effect.mp3";
				this.singleSoundAudioContext.src = "/static/audio/signle-sound-effect.mp3";
			},
			fail: (e) => {
				this.connectFirst = false
			},
			complete: () => {}
		});
		this.socketTask.onOpen(() => {
			if (this.socketStatus < 0) {
				this.socketStatus = 0
				const content = {
					message_type: 'init',
					token: this.token
				}
				this.socketTask.send({
					data: JSON.stringify(content),
					complete: () => {
						this.socketStatus = 1
					}
				});
			}

			setTimeout(() => {
				getSingleSessionList();
				getGroupSessionList();
				getNoticeList();
			}, 0)

		})
		this.socketTask.onClose((e) => {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '已退出聊天'
			// })
			uni.$emit('chatClose');
			if (this.socketStatus >= 0) {
				this.socketStatus = -99;
			}
			// this.reconnection();
		});

		this.socketTask.onError((e) => {
			// uni.showToast({
			// 	icon: 'none',
			// 	title: '已和聊天服务器断开'
			// })
			uni.$emit('chatError')
			this.socketStatus = -2;
			this.reconnection();
		});

		this.socketTask.onMessage((res) => {
			const data = JSON.parse(res.data);
			switch (data['message_type']) {
				case 'login_success':
					// 客户端登录成功
					// 做一个判断防止其他设备登录后，本设备一样通知login_success
					if (this.socketStatus != 99) {
						this.socketStatus = 99;
						// refreshFriendApplyMessage();
						// Service.refreshMemberData();
						uni.$emit('login_success');
						setTimeout(() => {
							this.connectFirst = false;
						}, 500)
					}
					break;
				case 'login_error':
					// 客户端登录失败
					this.close()
					uni.$emit('login_success');
					break;
				case 'ping':
					// 服务端ping客户端
					console.log('ping')
					this.socketTask.send({
						data: '{"message_type":"pong"}'
					});
					break;
				case 'logout':
					// 退出登录而离线
					if (store.state.user.setting.chatStatusSound) {
						this.chatStatusAudioContext.play()
					}
					commonUpdateIMUserOnlineStatus({
						id: data.id,
						status: 'offline'
					})
					uni.$emit('chatLogout', {
						id: data.id
					})
					break;
					// case 'logMessage':
					// 	let logMessage = data.data;
					// 	logMessage.timestamp = logMessage.timestamp / 1000
					// 	uni.$emit('chatMessage', {
					// 		data: logMessage
					// 	})
					// 	pushIMSessionList({
					// 		message: logMessage,
					// 		sessionId: `${logMessage.type}-${logMessage.id}`,
					// 		sessionUser: {
					// 			avatar: logMessage.avatar,
					// 			nickName: logMessage.nickName
					// 		}
					// 	})
					// 	break;
				case 'chatMessage':
					// 用户接受聊天数据，我会在这里主动将时间*1000用来适应Momentjs，同时直接压入IM消息回话中
					if (store.state.user.setting.chatSingleSound) {
						this.singleSoundAudioContext.play()
					}
					getSingleSessionList();
					let chatMessage = data.data;
					uni.$emit('chatMessage', {
						data: chatMessage
					})
					break;
				case 'groupMessage':
					// 用户接受聊天数据，我会在这里主动将时间*1000用来适应Momentjs，同时直接压入IM消息回话中
					if (store.state.user.setting.chatGroupSound) {
						this.groupSoundAudioContext.play()
					}
					getGroupSessionList();
					let groupMessage = data.data;
					uni.$emit('groupMessage', {
						data: groupMessage
					})
					break;
				case 'noticeMessage':
					// 用户接受消息通知
					getNoticeList();
					let noticeMessage = data.data;
					uni.$emit('noticeMessage', {
						data: noticeMessage
					})
					break;
				case 'recallMessage':
					// 用户接受消息通知
					console.log(data.data)
					// let noticeMessage = data.data;
					getGroupSessionList();
					getSingleSessionList();
					uni.$emit('recallMessage', {
						data: data.data
					})
					break;
				default:
					break;
			}
		})
	}
}

const commonUpdateIMUserOnlineStatus = (args) => {
	changeFiendOnlineStatus(args)
	updateSessionListItemOnlineStatus(args)
}


export {

	ChatIM
}
